package com.night.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.night.common.entity.ResultVo;
import com.night.common.entity.StatusCode;
import com.night.common.entity.role.MenuPerm;
import com.night.gateway.feign.PermManagerFeign;
import com.night.gateway.jwtUtil.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @author rzh6230
 * 2022/10/1 10:45
 */
@Component
public class PermFilter implements GlobalFilter, Ordered {
    @Autowired
    private PermManagerFeign permManagerFeign;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if ("/api/v1/role/login".equals(request.getURI().getPath())) {
            return chain.filter(exchange);
        }
        List<String> list = request.getHeaders().get("jwt");
        if (list == null || list.isEmpty()){
            return exchange.getResponse().writeWith(Mono.just(result(exchange, new ResultVo<>(StatusCode.TOKEN_FAIL))));
        }
        String token = list.get(0);
        boolean jwt = false;
        try {
            jwt = jwtUtils.verifyJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            return exchange.getResponse().writeWith(Mono.just(result(exchange, new ResultVo<>(StatusCode.TOKEN_FAIL))));
        }
        if (!jwt) {
            return exchange.getResponse().writeWith(Mono.just(result(exchange, new ResultVo<>(401, "身份信息失效"))));
        }
        int roleId = (int) JwtUtils.getInfo(token, "roleId");
        System.out.println(request.getURI().getPath());
        List<MenuPerm> data = permManagerFeign.getPermByRoleId(roleId).getData();
        for (MenuPerm perm : data) {
            if (request.getURI().getPath().matches(perm.getPerms())) {
                System.out.println("授权通过");
                return chain.filter(exchange);
            }
        }
        System.out.println("授权失败");
        return exchange.getResponse().writeWith(Mono.just(result(exchange, new ResultVo<>(StatusCode.NO_PERM))));
    }

    public DataBuffer result(ServerWebExchange exchange, ResultVo<?> resultVo) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = null;
        try {
            bytes = new ObjectMapper()
                    .writeValueAsString(resultVo).getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        //response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
        //response.getHeaders().add("token", "token");
        return dataBuffer;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
